<template>
  <div >
    <n-card title="小程序功能列表" header>
      <div class="header" >
        <div>
          <NButton type="primary" @click="onClickAdd">
            添加小程序功能
          </NButton>
        </div>
        <div>
          <n-input-group>
              <n-input v-model:value="params.keyword" clearable placeholder="请输入商品分类关键词" :style="{ width: '100%' }" />
              <n-button @click="categoryList" type="primary" ghost>
                搜索
              </n-button>
            </n-input-group>
        </div>
      </div>
    </n-card>
    <div class="box" :style="'height:'+innerHeights">
       <!-- 数据表 -->
      <div class="table-box">
 
          <n-data-table
            :loading="messageParams.loading"
            ref="table"
            :columns="columns"
            :data="data"
   
          />
        </div>
      
    </div>
     <div class="pagination">
            <div>共{{pagination.total}}条数据</div>
            <div>
              <n-pagination
              :page="params.pageNum"
              :page-size="params.pageSize"
              :item-count="pagination.total"
              size="medium"
              show-size-picker
              :page-slot="8"
              :page-sizes="pageSizes"
              :on-update:page="pageNext"
              :on-update:page-size="sizeNext"
            />
            </div>
        </div>

  
  <yingModal  :title="popTitle" @close="cancelCallback" @confirm="submitCallback" :SkuShow="showModal" >
        <template #content>
          <n-form
          ref="formRef"
          :model="formValue"
          :rules="rules"
          style=" display: grid;width: 100%;
            grid-template-columns: repeat(2, 1fr);gap:15px"
        >
          <n-form-item label="同步插件权限" path="name">
              <n-select  placeholder="请选择功能类型" v-model:value="formValue.plugin_id"
              :style="{ width: '400px' }" 
              filterable 
              :options="pluginOption"
              clearable
              label-field="title"
              :disabled="popTitle=='编辑'?true:false"
              value-field="plugin_id"
            />
          </n-form-item>
          <n-form-item label="功能名称" path="title">
            <n-input v-model:value="formValue.title" placeholder="请输入功能名称" />
          </n-form-item>
          <n-form-item label="功能路由" path="name">
            <n-input v-model:value="formValue.name" placeholder="请输入功能路由" />
          </n-form-item>
           <n-form-item label="功能排序" path="menuRank">
            <n-input v-model:value="formValue.menuRank" placeholder="请输入功能排序" />
          </n-form-item>
           <n-form-item label="功能类型" path="name">
              <n-select  placeholder="请选择功能类型" v-model:value="formValue.menuType"
              :style="{ width: '400px' }" 
              filterable 
              :options="menuType"
              clearable
            />
          </n-form-item>
          
           <n-form-item label="权限标识">
            <n-input v-model:value="formValue.auths" placeholder="请输入权限标识" />
          </n-form-item>
          <n-form-item label="功能链接">
            <n-input v-model:value="formValue.frameSrc" placeholder="请输入功能链接" />
          </n-form-item>
          <n-form-item label="功能Icon" path="name">
           
            <div @click="uploadShow=true" v-if="formValue.icon" style="height:135px;width:100px;overflow: hidden;display: flex;padding:12px;
                justify-content: center; align-items: center;">
                <n-image
                :preview-disabled="true"
                style="object-fit: contain;display: flex;
                    justify-content: center;
                    align-items: center;"
                :src="Https()+formValue.icon"/>
            </div>
             <div v-else @click="uploadShow=true" class="imageUpload">
              <n-icon size="24" color="rgb(49, 108, 114)">
                <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 16 16"><g fill="none"><path d="M8 2.5a.5.5 0 0 0-1 0V7H2.5a.5.5 0 0 0 0 1H7v4.5a.5.5 0 0 0 1 0V8h4.5a.5.5 0 0 0 0-1H8V2.5z" fill="currentColor"></path></g></svg>
              </n-icon>
            </div>
            <!-- <n-input v-model:value="formValue.image" placeholder="请输入商品分类图片" /> -->
          </n-form-item>
          <n-form-item label="状态" path="showLink">
            <n-switch 
            @update:value="handleUpdateValue"
            v-model:value="formValue.showLink">
              <template #checked>
                启动
              </template>
              <template #unchecked>
                禁用
            </template>
            </n-switch>
          </n-form-item>
        </n-form>
     
        </template>
    </yingModal>

   
    
    <yingModal  :title="'新增商品规格模版'" @close="uploadShow=false" @confirm="uploadShow=false" :SkuShow="uploadShow" >
        <template #content>
          <Upload type="1" @selectImage="selectImageFun"/>
        </template>
    </yingModal>
    
  </div>
</template>

<script setup lang="ts">
import yingModal from "@/components/common/YingModal.vue"
import { NAvatar, NButton, NImage, NSwitch, NTag  } from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { nextTick, onMounted, ref } from 'vue'
import { Https,setPagination } from "@/utils"
import api from './api'
import Upload from "@/views/upload/index.vue"
// const router = useRouter()
const innerHeights =ref(0);
onMounted(() => {
  innerHeights.value = String(window.innerHeight - 280)+'px'
  categoryList()
  myPlugin()
})

function handleUpdateValue(value: string) {
    if(value){
      formValue.value.status = true
      $message.success("启用")
    }else{
      $message.error("禁用")
      formValue.value.status = false
    }
    
  }

const pageSizes = [
  {
    label: '10 每页',
    value: 10
  },
  {
    label: '20 每页',
    value: 20
  },
  {
    label: '30 每页',
    value: 30
  },
  {
    label: '40 每页',
    value: 40
  }
]


const pagination = ref({
  total:10
  
})
const formRef = ref<FormInst | null>(null);

const showModal = ref(false);
const uploadShow = ref(false);
const popTitle = ref('添加小程序功能');
const params = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
})
const messageParams: any = ref({
  show: false,
  status: '403',
  loading: true,
})

const messageList: any = ref([
  {
    status: '500',
    title: '500 服务器错误',
    description: '服务器出错可能说明该雇更多程序员了',
    button: '散财消灾',
  },
  {
    status: '404',
    title: '404 资源不存在',
    description: '生活总归带点荒谬',
    button: '找点乐子吧',
  },
  {
    status: '403',
    title: '403 禁止访问',
    description: '总有些门是对你关闭的',
    button: '放轻松',
  },
])

const formValue = ref({})

const menuType = [
  {
    label:'菜单',
    value:3
  },
  {
    label:'按钮',
    value:4
  },
   
]

const pluginOption = ref([])



// const pagination = { pageSize: 10 ,page:1}
// {
//     label: () => h('span', { style: { color: 'red' } }, '删除'),
//     key: 'delete'
//   }

const rules = {

  title: {
    required: true,
    message: '请输入',
    trigger: 'blur'
  },
  menuRank: {
    required: true,
    message: '请输入',
    trigger: 'blur'
  },
  name: {
    required: true,
    message: '请输入',
    trigger: ['input']
  },

  icon: {
    required: true,
    message: '请输入',
    trigger: ['input']
  },
   menuType: {
    required: true,
    message: '请输入',
    trigger: ['change','select']
  },
  // status: {
  //   required: true,
  //   message: '状态',
  //   trigger: ['input','image']
  // }
}

const columns = [
  {
    title: 'ID',
    key: 'id',

    ellipsis: true,
  },
  {
    title: '名称',
    key: 'title',
    // width: 200,
    ellipsis: true,
  },
  {
    title: '路由',
    key: 'name',
  },
  {
    title: '图片',
    render: ({ icon }) => {
      // console.log(image)
      return h(NImage, {
        width: 60,
        src: Https()+icon,
      })
    },

  },
  {
    title: '链接',
    key: 'frameSrc',
  },
   {
    title: '权限标识',
    key: 'auths',
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => handleOpenRolesSet(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-fe:database' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },

]
const data: any = ref([])

async function handleDelete(id){
  const res: any = await api.categoryDeleteApi({
    id:id
  })

  if(res.code == 200){
    categoryList();
    $message.success('删除成功!')
  }else{
    
  }

}

const handleOpenRolesSet =(item) =>{
  formValue.value = item;
  formValue.value.menuRank = String(formValue.value.menuRank)
  popTitle.value = '编辑';
  showModal.value = true;
} 

const selectImageFun =(selectImageList) =>{
  formValue.value.icon = selectImageList[0];  // 只获取第一张图
  uploadShow.value =false
} 

async function myPlugin() {
  try {
    const res: any = await api.myPluinApi()
    if (res.code == 200) {
      console.log(res.data.list)
      pluginOption.value = res.data.list
    }

    
  }
  catch (error) {
    console.error(error)
  }
}

async function categoryList() {
  try {
    messageParams.value.loading = true
    const res: any = await api.categoryListApi(params.value)
    if (res.code == 200) {
      messageParams.value.loading = false
      pagination.value.total = res.data.total
      data.value = res.data.list
    }
    else {
      messageParams.value.show = false
      messageParams.value.status = '500'
    }
  }
  catch (error) {
    console.error(error)
  }
}
function onClickAdd(){
  popTitle.value = '添加小程序功能'
  formValue.value = {
    title:"",
    menuType:null,
    name:"",
    icon:"",
    auths:"",
    status:true,
    frameSrc:"",
    showLink:true,
    menuRank:null,
    plugin_id:null
  }
  showModal.value = true
}
async function submitCallback() {
  messageParams.value.loading = true
  formRef.value?.validate((errors) => {
    if (!errors) {
      if(popTitle.value == '添加小程序功能')
        categoryAddFun();
      else
        categoryEditFun();
    }
    else {
      showModal.value = true
      return 
 
    }
  })
}

async function categoryAddFun(){
  const res: any = await api.categoryAddApi(formValue.value)
  if(res.code == 200){
    categoryList();
    
    $message.success('添加成功!')
  }else{
    $message.error(res.message)
    messageParams.value.loading = false;
  }
}

async function categoryEditFun(){
  const res: any = await api.categoryEditApi(formValue.value)
  if(res.code == 200){
    categoryList();
    $message.success('编辑成功!')
  }else{
    $message.error(res.message)
  }
}

function pageNext(page){
  params.value.pageNum = page
  categoryList();
}
function sizeNext(size){
  params.value.pageNum = 1
  params.value.pageSize = size
  categoryList();
}


function cancelCallback() {
  categoryList();
  showModal.value = false
}
</script>

<style scoped>
 .box {
    height: 75vh;
    /* overflow-y: auto; */
}
.table-box{
  padding: 20px;
}
.box-modal{
  /* width: 600px; */
  /* height: 350px; */
  /* overflow-y: auto; */
}
.pagination{
  display: flex;
  justify-content: right;
  /* height: 60px; */
  gap: 10px;
  align-items: center;
  position: relative;
  top: 20px;
  right: 30px;
}
.header{
  display: flex;gap: 10px;
}
.box-upload{      
  /* width: 1000px; */
  height: 650px;
  width: 100%;
  /* background: white; */
}
.imageUpload{
  width:100px;
  height:100px;
  border:1px solid #eee;
  display: flex;
  justify-content: center;
  border-radius: 6px;
  align-items: center;
}
.imageUpload:hover{
  border:1px solid rgb(49, 108, 114);
}
</style>
